package controller;

import helper.Balance;
import helper.Formatter;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import model.*;
import org.mybeans.dao.DAOException;

import databeans.*;

/*
 * @Xiao Liang
 * Customer Use Case: View Account
 */
public class CustomerViewAccountAction extends Action{

	private PositionDAO positionDAO; 
	private TransactionDAO transactionDAO; 
	private FundHistoryDAOSQL fundHistoryDAOSQL; 
	private FundDAO fundDAO; 

	public CustomerViewAccountAction(Model model) {
		positionDAO = model.getPositoinDAO(); 
		fundHistoryDAOSQL = model.getFundHistoryDAOSQL(); 
		transactionDAO = model.getTransactionDAO(); 
		fundDAO = model.getFundDAO(); 
	}

	public String getName() { return "customerViewAccount.do"; }

	public String perform(HttpServletRequest request) {
        // define target page
		String loginPage = "customer/customer-login.jsp";
        String successPage = "customer/view-account.jsp"; 
        
        // Set up the errors list
        List<String> errors = new ArrayList<String>();
        request.setAttribute("errors",errors);
        
		try {
	        
	        //check if customer has actually logged in
	        Customer customer = (Customer) request.getSession(true).getAttribute("customer");
	        if (customer == null) {
	            errors.add("You need to log in before viewing this page");
	            System.out.println("Customer is null"); 
	            return loginPage;
	        }
			//get customer id
  			int customerID = customer.getCustomerID(); 
  			
  			//display name
  			String firstName = customer.getFirstName();
  			String lastName  = customer.getLastName();
  			String name      = firstName+" "+lastName; 
  			
  			request.setAttribute("name", name); 
  			request.setAttribute("page", "view-acc");
  			
  			//display address
  			String addrLine1 = customer.getAddrLine1();
  			String addrLine2 = customer.getAddrLine2();
  			String addr; 
  			if(addrLine2!=null) addr = addrLine1+" "+addrLine2; 
  			else addr=addrLine1; 
  			request.setAttribute("address", addr); 
  			
  			//display date of last trading day
  			Date lastTradingDate = transactionDAO.getLastTradingDate(customerID); 
  			String lastTradingDateString=null; 
  			Date lastSubmissionDate = transactionDAO.getLastSubmissionDate(customerID); 
  			String lastSubmissionDateString=null; 
  			/*new Date(18000) is default date*/
  			if(lastTradingDate.equals(new Date(18000))){
  				SimpleDateFormat sdf = new SimpleDateFormat("dd MMM, yyyy"); 
  				if(!(lastSubmissionDate.equals(new Date(18000))))lastSubmissionDateString = sdf.format(lastSubmissionDate); 
  				else lastSubmissionDateString=" - ";
  			}else {
  				SimpleDateFormat sdf = new SimpleDateFormat("dd MMM, yyyy"); 
  				lastTradingDateString = sdf.format(lastTradingDate);  
  			}
  			request.setAttribute("lastTradingDate", lastTradingDateString);
  			request.setAttribute("lastSubmissionDate", lastSubmissionDateString);
  			
  			
  			//display email
  			String email     = customer.getEmail();  
  			request.setAttribute("email",email);
  			
  			//display cash balance
  			long cash      = customer.getCash(); 
  			request.setAttribute("cashBalance", Formatter.prepCashToView(cash)); 
  			
  			//display available cash
  			long availableCash = Balance.getCustomerAvailableCash(customer); 
  			request.setAttribute("availableCash", Formatter.prepCashToView(availableCash)); 
  			
  			/*
  			 * display number of shares of each fund owned
  			 * : get Positions with customerID
  			 * to retrieve fundID: position[i].getFundID();
  			 * to retrieve shares: position[i].getShares(); 
  			 */
  			 Position[] positions = positionDAO.getPositions(customerID); 
  			 request.setAttribute("positions", positions); 
  			 
  			/*
  			 * display the value of that position = shares * price of fund 
  			 * : obtain a list of value corresponding to fund
  			 */
  			 List<Long> values = new ArrayList<Long>();
  			 
   			/*
   			 * display the fund name
   			 * : obtain a list of fundName corresponding to fund id
   			 */
  			 List<String> fundNames = new ArrayList<String>(); 
  			 
  			 for (int i=0; i<positions.length; i++){
  			 	long shares             = positions[i].getShares();
  			 	int fundID              = positions[i].getFundID(); 
  			 	
  			 	Fund fund = fundDAO.lookup(fundID);
  			 	fundNames.add(fund.getName()); 
  			 	
  			 	Calendar cal = Calendar.getInstance();
  			 	cal.setTime(lastTradingDate); 
  			 	
  			 	FundHistory fundHistory = fundHistoryDAOSQL.lookup(fundID,cal); 
  				if(fundHistory==null) {
  					values.add(Long.parseLong("0"));  //if no fund history, transaction is pending, position is zero. 
  				}else{  	
  					long price = fundHistory.getPrice(); 
  					long valueMoney = price * shares;
  					values.add(valueMoney); 
  				}
  	     	}
  			request.setAttribute("values", values); 
  			request.setAttribute("fundNames", fundNames); 

	        return successPage;
        } catch (DAOException e) {
        	errors.add(e.getMessage());
        	return successPage;
        }
    }
	
}
